<?php
namespace app\api\controller;

use app\common\controller\Api;

class Comment extends Api{
    
    private $model;
    
    protected $noNeedLogin = [];
    protected $noNeedRight = '*';
    
    public function _initialize(){
        parent::_initialize();
        
        $this->model = model('comment');
    }
    
    public function comment(){
        $uid = $this->request->post('uid');
        $mobile = $this->request->post('mobile');
        $nick = $this->request->post('nick');
        $email = $this->request->post('email');
        $content = $this->request->post('content');
        
        if (!$uid || !$mobile || !$nick || !$email || !$content)
        {
            $this->error(__('Invalid parameters'));
        }
        
        $count = $this->model->where(['uid'=>$uid])->count();
        if($count >= 3)
        {
            $this->error(__('Not Enough Comment Count'));
        }
        
        $data = ['uid'=>$uid, 'content'=>$content, 'email'=>$email, 'nick'=>$nick, 'mobile'=>$mobile];
        $res = $this->model->allowField(true)->save($data);
        model('User')->where(['id'=>$uid])->setInc('comment');  // 留言数量 +1
        if ($res) {
            $this->success('返回成功', ['count'=>$count + 1]);
        } else {
            $this->error(__('Operation failed'));
        }
    }
    
    public function count(){
        $uid = $this->request->post('u');
        
        if (!$uid)
        {
            $this->error(__('Invalid parameters'));
        }
        
        $count = $this->model->where(['uid'=>$uid])->count();
        
        $this->success('返回成功', ['count'=>$count]);
    }
    
}